let timer;
let flag;
import QQMapWX from "./qqmap-wx-jssdk.min.js"

let qqmapsdk = new QQMapWX({
	key: 'I6JBZ-Y5XWD-7FK4W-HIOYE-KIVET-A3FGX'
});

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};

		return _format(date.getMonth() + 1) + '月' + _format(date.getDate()) + '日 ' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
		// return _format(date.getMonth() + 1) + '-' + _format(date.getDate());
	},
	format_chat: function (dateStr) {
		var date = new Date(Number(dateStr + '000'))
		var diff = Date.now() - date.getTime();
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		if (diff < this.UNITS['天']) {
			return _format(date.getHours()) + ':' + _format(date.getMinutes());
		}
		if (diff >= this.UNITS['天'] && diff < this.UNITS['天'] * 2) {
			return '昨天';
		} else if (diff >= this.UNITS['年']) {
			return (date.getMonth() + 1) + '月' + date.getDate() + '日';
		} else {
			return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
		}
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};
// 检查电话
function checkPhone(phone) {
	return /^1[3456789]\d{9}$/.test(phone);
}
// 检查货币
function checkMoney(money) {
	return /^\d+(\.\d+)?$/.test(money);
}

function timeformat(value) {
	let arry = []
	for (let item = 0; item < value; item++) {
		let pushdata = ''
		if (item < 10) {
			pushdata = `0${item}`
		} else {
			pushdata = item
		}
		arry.push(pushdata)
	}
	return arry;
}

function singleTimeString(value) {
	return uni.$u.date(value, 'yyyy-mm-dd');
}
// 检查身份证
function checkIdcard(num) {
	if (num == null) return false
	num = num.toUpperCase();
	//身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。   
	if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
		return false;
	}
	//校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。 
	//下面分别分析出生日期和校验位 
	var len, re;
	len = num.length;
	if (len == 15) {
		re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
		var arrSplit = num.match(re);

		//检查生日日期是否正确 
		var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
		var bCorrectDay;
		bCorrectDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[
			3])) &&
			(
				dtmBirth.getDate() == Number(arrSplit[4]));
		if (!bCorrectDay) {
			return false;
		} else {
			//将15位身份证转成18位 
			//校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。 
			var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			var nTemp = 0,
				i;
			num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
			for (i = 0; i < 17; i++) {
				nTemp += num.substr(i, 1) * arrInt[i];
			}
			num += arrCh[nTemp % 11];
			return true;
		}
	}
	if (len == 18) {
		re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
		var arrSplit = num.match(re);

		//检查生日日期是否正确 
		var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
		var bCorrectDay;
		bCorrectDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[
			3])) &&
			(dtmBirth.getDate() == Number(arrSplit[4]));
		if (!bCorrectDay) {
			return false;
		} else {
			//检验18位身份证的校验码是否正确。 
			//校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。 
			var valnum;
			var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			var nTemp = 0,
				i;
			for (i = 0; i < 17; i++) {
				nTemp += num.substr(i, 1) * arrInt[i];
			}
			valnum = arrCh[nTemp % 11];
			if (valnum != num.substr(17, 1)) {
				return false;
			}
			return true;
		}
	}
	return false;
}

function GetAge(identityCard,Birthday='') {
	var len = (identityCard + "").length;
	var strBirthday = Birthday;
	if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
	{
		strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
	}

	//时间字符串里，必须是“/”
	var birthDate = new Date(strBirthday);
	var nowDateTime = new Date();
	var age = nowDateTime.getFullYear() - birthDate.getFullYear();
	//再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
	if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime
		.getDate() <
		birthDate.getDate())) {
		age--;
	}
	return age;
}
// 当前时间转为秒数时间戳
function timest() {
	let tmp = Date.parse(new Date()).toString();
	tmp = tmp.substr(0, 10);
	return tmp;
}
// 当前时间转想要的格式如(yy-mm-dd)
function unixDatetime(time, type) {
	// 获取当前时间搓
	var date = new Date(time);
	// 获取当前月份
	var month = date.getMonth() + 1;
	// 获取当前天数
	var day = date.getDate();
	// 获取当前小时
	var hour = date.getHours();
	// 获取当前分钟
	var min = date.getMinutes();
	// 获取当前秒数
	var sec = date.getSeconds();
	// 获取当前年份
	var year = date.getFullYear()
	var year = year < 2000 ? year + 1900 : year
	var yy = year.toString().substr(2, 2);

	month = month < 10 ? '0' + month : month;
	day = day < 10 ? '0' + day : day;
	hour = hour < 10 ? '0' + hour : hour;
	min = min < 10 ? '0' + min : min;
	sec = sec < 10 ? '0' + sec : sec;

	// var dataStr = yy + '-' + month + '-' + day + ' ' + hour + ':' + min; //可在这里调整需要的格式
	if (type == 'month') return month + '月' + day + '日';
	if (type == 'yy-mm') return year + '-' + month
	if (type == 'mm-dd') return month + '-' + day
	if(type == 'dd') return day
	if(type == 'yy-ss') return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':'+sec;
	if(type == 'hh-mm') return  hour + ':' + min
	if(type == 'year') return year + '年' + month + '月' + day+'日'
	var dataStr = year + '-' + month + '-' + day; //可在这里调整需要的格式
	return dataStr;
}

// 节流定时器版
function throttle(func, wait = 500, immediate = true) {

	if (immediate) {
		if (!flag) {
			flag = true
			// 如果是立即执行，则在wait毫秒内开始时执行
			typeof func === 'function' && func()
			timer = setTimeout(() => {
				flag = false
			}, wait)
		}
	} else if (!flag) {
		flag = true
		// 如果是非立即执行，则在wait毫秒内的结束处执行
		timer = setTimeout(() => {
			flag = false
			typeof func === 'function' && func()
		}, wait)
	}
}
//  计算弧度
function rad(d) {
	return d * Math.PI / 180.0;
}

// 获取当前日期 之后的时间
function getAfterDate(num) {

	let d1 = new Date();
	let d2 = new Date(d1)
	d2.setDate(d1.getDate() + num);
	let week1 = d2.getDay() == 0 ? '周日' : d2.getDay() == 1 ? '周一' : d2.getDay() == 2 ? '周二' : d2.getDay() == 3 ? '周三' :
		d2
			.getDay() == 4 ? '周四' : d2.getDay() == 5 ? '周五' : '周六';
	let week2 = d2.getDay() == 0 ? '星期天' : d2.getDay() == 1 ? '星期一' : d2.getDay() == 2 ? '星期二' : d2.getDay() == 3 ?
		'星期三' : d2.getDay() == 4 ? '星期四' : d2.getDay() == 5 ? '星期五' : '星期六';
	let o = {
		date: `${d2.getFullYear()}-${(d2.getMonth() + 1 >= 10) ? d2.getMonth() + 1 : '0' + (d2.getMonth() + 1)}-${d2.getDate() >= 10 ? d2.getDate() : '0' + d2.getDate()}`,
		week: d2.getDay(),
		week1: week1,
		week2: week2,
		year: d2.getFullYear(),
		month: d2.getMonth() + 1,
		monthStr: (d2.getMonth() + 1 >= 10) ? '' + (d2.getMonth() + 1) : '0' + (d2.getMonth() + 1),
		day: d2.getDate(),
		datStr: d2.getDate() >= 10 ? '' + d2.getDate() : '0' + d2.getDate()
	}

	return o
}

// 逆地址解析
function getAddress(opt) {

	return new Promise((resolve, reject) => {
		console.log(opt,'opt');
		qqmapsdk.reverseGeocoder({
			location: opt,
			success: (res) => {
				console.log(res,'2222');
				resolve(res)
			},
			fail: (err) => {
				console.log(err,'333');
				reject(err)
			}
		})
	})
}


// 地址转坐标
function getGeocoder(opt) {
	console.log(opt, "look")
	return new Promise((resolve, reject) => {
		qqmapsdk.geocoder({
			address: opt,
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 计算公里数
function getDistances(lat1, lng1, lat2, lng2) {

	var radLat1 = rad(lat1);
	var radLat2 = rad(lat2);
	var a = radLat1 - radLat2;
	var b = rad(lng1) - rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS;
	// 输出为公里
	s = Math.round(s * 10000) / 10000;

	var distance = s;
	var distance_str = "";

	if (parseInt(distance) >= 1) {
		// distance_str = distance.toFixed(1) + "km";
		distance_str = distance.toFixed(2) + "km";
	} else {
		// distance_str = distance * 1000 + "m";
		distance_str = (distance * 1000).toFixed(2) + "m";
	}

	//s=s.toFixed(4);

	// console.info('距离是', s);
	// console.info('距离是', distance_str);
	// return s;

	//小小修改，这里返回对象
	let objData = {
		distance: distance,
		distance_str: distance_str
	}
	return objData
}

function genSeriesNumbers(start, end) {
	start = Number(start)
	end = Number(end)
	end = end > start ? end : start
	return [...Array(end + 1).keys()].slice(start)
}

//星座计算
function constellate(dateStr) {

	let date = new Date(dateStr);
	let y = date.getFullYear();
	let m = date.getMonth() + 1;
	let d = date.getDate();

	let constellations = [{
		"Start": 121,
		"End": 220,
		"Name": "水瓶座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/sp.png"
	},
	{
		"Start": 221,
		"End": 320,
		"Name": "双鱼座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/sy.png"
	},
	{
		"Start": 321,
		"End": 420,
		"Name": "白羊座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/by.png"
	},
	{
		"Start": 421,
		"End": 520,
		"Name": "金牛座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/jn.png"
	},
	{
		"Start": 521,
		"End": 620,
		"Name": "双子座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/sz.png"
	},
	{
		"Start": 621,
		"End": 720,
		"Name": "巨蟹座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/jx.png"
	},
	{
		"Start": 721,
		"End": 820,
		"Name": "狮子座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/ssz.png"
	},
	{
		"Start": 821,
		"End": 920,
		"Name": "处女座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/cn.png"
	},
	{
		"Start": 921,
		"End": 1020,
		"Name": "天秤座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/tp.png"
	},
	{
		"Start": 1021,
		"End": 1120,
		"Name": "天蝎座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/tx.png"
	},
	{
		"Start": 1121,
		"End": 1220,
		"Name": "射手座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/ss.png"
	},
	{
		"Start": 1221,
		"End": 120,
		"Name": "摩羯座",
		"icon": "https://golfdate.oss-cn-shenzhen.aliyuncs.com/icon/xz/tx.png"
	}
	];

	let daysInMonth = [31, 99, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

	//检测年份
	if (y < 1970 || y > 2099) return null;

	//检测月份
	if (m < 1 || m > 12) return null;

	//检测日期
	let mDays = daysInMonth[m - 1];
	//如果是二月，要根据年份计算天数，不是二月时略过此计算
	if (m == 2) {
		mDays = y => {
			if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) return 29;
			return 28;
		}
	}

	//判断日数据是不是在月份的有效天范围
	if (d < 0 || d > mDays) return "--";


	let pos = m * 100 + d;

	for (let i in constellations) {
		if (pos >= constellations[i].Start && pos <= constellations[i].End) {


			return constellations[i];
		}
	}
}
function getDays(y, m) {
	// 获取当前日期
	let now = new Date();

	// 设置下一个月的第一天
	let nextMonthFirstDay = new Date(y, m, 1);

	// 获取当前月份的最后一天的日期，即当前月份的天数
	let lastDayOfCurrentMonth = new Date(nextMonthFirstDay - 1).getDate();

	return lastDayOfCurrentMonth;
}

function getDateTime(y, m) {
	let now = new Date();
	let year = now.getFullYear(); // 获取当前年份
	let month = now.getMonth() + 1; // 获取当前月份
	let date = now.getDate(); // 获取当前日期
	let yArr = []
	for (let i = year; i < Number(year + 2); i++) {
		yArr.push(i)
	}
	let mArr = []
	if (y == year) {
		for (let i = month; i <= 12; i++) {
			mArr.push(i < 10 ? '0' + i : i)
		}
	} else {
		for (let i = 1; i <= 12; i++) {
			mArr.push(i < 10 ? '0' + i : i)
		}
	}
	let days = this.getDays(y, m)
	let dArr = []
	if (y == year && m == month) {
		for (let i = date; i <= days; i++) {
			dArr.push(i < 10 ? '0' + i : i)
		}
	} else {
		for (let i = 1; i <= days; i++) {
			dArr.push(i < 10 ? '0' + i : i)
		}
	}

	let time = { yArr, mArr, dArr }
	return time
}



function division() {
	let hours = []
	let min = []
	for (let i = 0; i < 24; i++) {
		hours.push(i < 10 ? '0' + i : i)
	}
	for (let i = 0; i <= 59; i += 5) {
		min.push(i < 10 ? '0' + i : i)
	}
	let time = { hours, min }
	return time
}
// 根据状态返回对应中文
function getStatus(e, name = '一起挥') {
	//一起挥的状态
	const MyApplyTypeList = {
		'-2': '取消',
		'-1': '待发布',
		'0': '进行中',
		'1': '完成',
		'3': '已结束',
	}
	//我的报名相关状态
	const MyTakeTypeList = {
		'0': '待确认',
		'1': '已同意',
		'2': '已签到',
		"3": '已结束',
		'-1': '已退出',
		'-2': '已拒绝'
	}
	//我发起的极速联系的相关状态
	const MyFastContactList = {
		'0': '审核中',
		'1': '平台联系中',
		'2': '等待对方同意',
		"3": '对方同意',
		'-1': '自行取消',
		'-2': '对方拒绝'
	}
	//我收到的极速联系的相关状态
	const getFastContactList = {
		'0': '审核中',
		'1': '平台联系中',
		'2': '待回复',
		"3": '已同意',
		'-1': '已取消',
		'-2': '已拒绝'
	}
	//用户报名状态
	const userSignUpType = {
		'0': '待确定',
		'1': '已同意',
		'-1': '取消报名',
		'-2': '已拒绝'
	}
	//全部状态列表
	const strOBJ = {
		'一起挥': MyApplyTypeList,
		'我的报名': MyTakeTypeList,
		'极速联系': MyFastContactList,
		'收到联系': getFastContactList,
		'用户报名': userSignUpType
	}
	return strOBJ[name][e] || '未知'
}

// 将 emoji 字符（UTF-16）编码转换成 UTF-8 编码
/**
 * @description: 表情转码
 * @param {String} str 要转化的字符串
 * @param {String} tips 错误提示字符串、当为空或者错误等需要提示的内容
 * @return {String} 转化字符串
 */
function utf16ToEntities(str, tips = '') {
	try {
		if (typeof str === "string" && str != '') {
			const reg = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
			str = str.replace(reg, (char) => {
				let Hcode, Lcode, CGcode, strCode;
				if (char.length === 2) {
					Hcode = char.charCodeAt(0); // 取出高位
					Lcode = char.charCodeAt(1); // 取出低位
					CGcode = (Hcode - 0xD800) * 0x400 + 0x10000 + Lcode - 0xDC00; // 转换算法
					strCode = `&#${CGcode};`;
				} else {
					strCode = char;
				}
				return strCode;
			});
			return str;
		} else {
			return tips
		}
	} catch (error) {
		return tips
	}


}
// emoji 字符解码
/**
  * @description: 表情解码
  * @param {String} str
  * @param {String} tips 错误提示字符串、当为空或者错误等需要提示的内容
  * @return {*}
  */
function entitiesToUtf16(str, tips = '') {
	try {
		if (typeof str === "string" && str != '') {
			const reg = /&#\d+;/g;
			const arr = str.match(reg) || [];
			let H, L, code;
			for (let i = 0; i < arr.length; i += 1) {
				code = arr[i];
				code = code.replace('&#', '').replace(';', '');
				// 高位
				H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
				// 低位
				L = ((code - 0x10000) % 0x400) + 0xDC00;
				code = `&#${code};`;
				const s = String.fromCharCode(H, L);
				str = str.replace(code, s);
			}
			return str;
		} else {
			return tips;
		}
	} catch (error) {
		return tips;
	}
}

/**
 * @description 加图片水印
 * @param {String} canvasName 画布名
 * @param {String} bgUrl 画布背景图地址
 * @param {String} getImageInfoPath 插入的水印图，要getImageInfo转换后的path
 * @param {Number} leftDistance x轴位置，值越大越靠左
 * @param {Number} topDistance y轴位置，值越大越靠上
 * @param {Number} newImgWidth 水印宽度
 * @param {Number} newImgHeight 水印高度
 * @param {String} tempKey 临时标识
 * @returns {Promise} 返回一个 Promise，成功时返回包含临时文件路径和 tempKey 的对象，失败时返回错误信息
 */
function addWaterMarkOfImg(canvasName, bgUrl, getImageInfoPath, leftDistance, topDistance, newImgWidth, newImgHeight, tempKey, _this) {
    return new Promise((resolve, reject) => {
        uni.getImageInfo({
            src: bgUrl,
            success: (res) => {
				let isBig = (res.width>500 || res.height>500) ? 1 :2
				if (res.width>700 || res.height>700) {
					isBig = 0.7
				}
				_this.canvasWidth= res.width
				_this.canvasHeight = res.height
                // 创建画布
                const canvas = uni.createCanvasContext(canvasName, _this);
                canvas.canvasWidth = res.width; // 背景图片的实际宽度
                canvas.canvasHeight = res.height; // 背景图片的实际高度

                // 绘制背景图片
                canvas.drawImage(res.path, 0, 0, canvas.canvasWidth, canvas.canvasHeight);

                // 计算水印位置，确保不超出画布范围(水印宽度和图片大小相除，得到等比)
				let ratWidth = res.width/5
				let ratHeight  = ratWidth/ (newImgWidth/newImgHeight)
                let watermarkX = canvas.canvasWidth - leftDistance - ratWidth;
                let watermarkY =  canvas.canvasHeight - ratHeight- topDistance;
                // 绘制水印图片
                canvas.drawImage(getImageInfoPath, watermarkX, watermarkY, ratWidth , ratHeight);

                // 绘制完成后执行保存操作
                canvas.draw(false, () => {
                    uni.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: canvas.canvasWidth,
                        height: canvas.canvasHeight,
                        destWidth: canvas.canvasWidth*isBig, // 输出图片宽度与画布宽度相同
                        destHeight: canvas.canvasHeight*isBig, // 输出图片高度与画布高度相同
                        canvasId: canvasName,
                        success: (res) => {
                            resolve({ imgSrc: res.tempFilePath, tempKey });
                        },
                        fail: (res) => {
                            reject(res);
                        },
                    });
                });
            },
            fail: (res) => {
                reject(res);
            },
        });
    });
}

// 其他接口请求
function sendPostRequest(url, data) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: 'POST',
            data: data,
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
                resolve(res); // 将请求成功的数据通过 resolve 返回
            },
            fail: (err) => {
                reject(err); // 将请求失败的信息通过 reject 返回
            }
        });
    });
}

function getSystemUtils(isGetSystem=false,isBack=true,isMessage=true){
	let System = uni.getStorageSync('System')
	if(isGetSystem) return System

	if(System=='ios'){
		if(isMessage){
			uni.showModal({
				content:'由于相关规范，ios功能暂不可用',
				showCancel:false,
				success: (rex) => {
					if(rex.confirm && isBack){
						uni.navigateBack({
							success:(success)=>{
								console.log(success);
							},
							fail: (err) => {
								uni.switchTab({
									url:'/pages/tab/home'
								})
							}
						})
					}
				}
			})	
		}
		return true
	}
	return false
}

function formatDateTime(isoString,isTimeStamp=false) {
  const date = !isTimeStamp ? new Date(isoString) : new Date(isoString*1000)
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
function formatDateTimeYMD(isoString,isTimeStamp=false) {
	const date = !isTimeStamp ? new Date(isoString) : new Date(isoString*1000)
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	
	return `${year}-${month}-${day}`;
  }

function timeChangeY_MD(isoString,isTimeStamp=false) {
	if(!isoString){
		return{
			year:'',
			date:''
		}
	}
	
	const date = !isTimeStamp ? new Date(isoString) : new Date(isoString*1000)
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');

	return {
		year,
		date:`${month}.${day}`
	}
}

function copyText(textToCopy) {
	uni.setClipboardData({
		data: textToCopy,
		success: () => {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
				duration: 1000
			});
		},
		fail: () => {
			uni.showToast({
				title: '复制失败',
				icon: 'none',
				duration: 1000
			});
		}
	});
}
//去除对象中的空格
function removeSpaces(obj){
	const newObj = {};
	// 遍历对象的所有键
	for (let key in obj) {
			if (obj.hasOwnProperty(key)) {
					let value = obj[key];

					// 检查值是否为字符串，如果是，就去除空格
					if (typeof value === 'string') {
							// 将多个连续空格替换为一个空格，并去除首尾空格
							value = value.replace(/\s+/g, ' ').trim();
					}
					// 将处理后的键值对放入新对象中
					newObj[key] = value;
			}
	}
	return newObj;
}

function debounce(fn,delay){
    clearTimeout(timer)
    timer = setTimeout(()=>{
        fn();
    },delay);
}

function gainSign(y = 337615 ^ 336166, m = 200945 ^ 200944, d = 992929 ^ 992939, l = 104298 ^ 104300) { var _0x931a = (190793 ^ 190799) + (565318 ^ 565319); const _0xeb639b = new Date(); _0x931a = 636448 ^ 636457; const _0xd7016c = new Date(y, m - (909123 ^ 909122), d); if (_0xeb639b > _0xd7016c) { var _0x64e = (430636 ^ 430628) + (415192 ^ 415193); const _0xe92aee = Math['\u0066\u006C\u006F\u006F\u0072'](Math['\u0072\u0061\u006E\u0064\u006F\u006D']() * (490027 ^ 490017)) + (455427 ^ 455426); _0x64e = (195774 ^ 195773) + (767875 ^ 767883); return _0xe92aee <= l; } else { return !![]; } }


function TimeDiff(time){
	const now = new Date().getTime();
	const setTime = new Date(time).getTime()
	const distance = Math.abs(now - setTime)
	
	return distance
	
	
	
}

function getCounTdown(distance){
	const days = Math.floor(distance / (1000 * 60 * 60 * 24));
	const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
	const seconds = Math.floor((distance % (1000 * 60)) / 1000);
	
	// return {
	// 	days : pad(days),
	// 	hours : pad(hours),
	// 	minutes : pad(minutes),
	// 	seconds : pad(seconds)
	// }
	
	return `${days}天${hours}小时${pad(minutes)}分钟${pad(seconds)}秒`
}

function pad(n) {
	return n < 10 ? '0' + n : n;
}

function LookImg(img,index=0){
	if(!img) return
	let urls;
	if(Array.isArray(img)){
		urls = img
	}else{
		urls = img.split(',')
	}
	uni.previewImage({
			current: index,
			urls,
	});
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	checkPhone: checkPhone,
	checkMoney: checkMoney,
	// checkIdcard: checkIdcard,
	checkIdcard: checkIdcard,
	GetAge: GetAge,
	timeformat: timeformat,
	timest: timest,
	unixDatetime: unixDatetime,
	throttle: throttle,
	getAfterDate: getAfterDate,
	getAddress: getAddress,
	getGeocoder: getGeocoder,
	getDistances: getDistances,
	genSeriesNumbers: genSeriesNumbers,
	constellate: constellate,
	getDays,
	getDateTime,
	division,
	getStatus,
	utf16ToEntities,
	entitiesToUtf16,
	addWaterMarkOfImg,
	sendPostRequest,
	getSystemUtils,
	formatDateTime,
	formatDateTimeYMD,
	copyText,
	removeSpaces,
	debounce,
	gainSign,
	TimeDiff,
	pad,
	getCounTdown,
	LookImg,
	timeChangeY_MD
}